{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 协同过滤(ALS)算法\n",
    "\n",
    "\n",
    "基于矩阵分解的协同过滤的标准方法中，“用户－商品”矩阵中的条目是用户给予商品的显式偏好"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下面的例子中，我们从MovieLens dataset读入评分数据，每一行包括用户、电影、评分以及时间戳。我们默认其排序是显式的来训练ALS模型。我们通过预测评分的均方根误差来评价推荐模型。如果评分矩阵来自其他信息来源，也可将implicitPrefs设置为true来获得更好的结果。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pyspark.ml.evaluation import RegressionEvaluator\n",
    "from pyspark.ml.recommendation import ALS\n",
    "from pyspark.sql import Row\n",
    " \n",
    "lines = spark.read.text(\"data/mllib/als/sample_movielens_ratings.txt\").rdd\n",
    "parts = lines.map(lambda row: row.value.split(\"::\"))\n",
    "ratingsRDD = parts.map(lambda p: Row(userId=int(p[0]), movieId=int(p[1]),\n",
    "                                     rating=float(p[2]), timestamp=long(p[3])))\n",
    "ratings = spark.createDataFrame(ratingsRDD)\n",
    "(training, test) = ratings.randomSplit([0.8, 0.2])\n",
    " \n",
    "# Build the recommendation model using ALS on the training data\n",
    "als = ALS(maxIter=5, regParam=0.01, userCol=\"userId\", itemCol=\"movieId\", ratingCol=\"rating\")\n",
    "model = als.fit(training)\n",
    " \n",
    "# Evaluate the model by computing the RMSE on the test data\n",
    "predictions = model.transform(test)\n",
    "evaluator = RegressionEvaluator(metricName=\"rmse\", labelCol=\"rating\",\n",
    "                                predictionCol=\"prediction\")\n",
    "rmse = evaluator.evaluate(predictions)\n",
    "print(\"Root-mean-square error = \" + str(rmse))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
